#include "stdafx.h"
#include "RenderTarget.h"

#include "Log.h"
#include "Exception.h"
#include "MemUtils.h"
#include "ErrorHandlers.h"

namespace Cvekas {

RenderTarget::RenderTarget(ResourceId id, D3DDevicePtr device, const std::string &name, uint width, uint height, D3DFORMAT format)
	:
Texture2D(id, device, name, format)
{
	this->width = width;
	this->height = height;

	usage = D3DUSAGE_RENDERTARGET;
	is_lockable = false;
	is_locked = false;
	is_ready = false;

	create();
}

RenderTarget::~RenderTarget()
{
	safeRelease(rt_surface);
	// No need to log this
	//if(!is_released)
	//	LOG(FORMAT("Render target %s released", % name));
}

IDirect3DSurface9* RenderTarget::getD3DSurface()
{
	return rt_surface;
}

void RenderTarget::onDeviceLost()
{
	LOG(FORMAT("Releasing render target %s", % name));
	is_released = true;
	is_ready = false;
	safeRelease(texture);
}

void RenderTarget::onDeviceReset()
{
	if(is_released)
	{
		create();
	}
}

void RenderTarget::create()
{
	LOG(FORMAT("Creating render target %s", % name));

	IDirect3DTexture9* temp_texture = static_cast<IDirect3DTexture9*>(texture);
	E_E(device->CreateTexture(width, height, 1, usage, format, D3DPOOL_DEFAULT, &temp_texture, NULL));
	E_E(temp_texture->GetSurfaceLevel(0, &rt_surface));
	E_E(temp_texture->GetLevelDesc(0, &description));

	texture = temp_texture;

	is_ready = true;
	is_released = false;
}
} // namespace